﻿#include "GameStateLayer.h"
#include "GameUtil.h"
#include "MainGameScene.h"


using namespace cocos2d::extension;

GameStateLayer::~GameStateLayer(void)
{
}

bool GameStateLayer::init(){  
	if (!CCLayer::init()) {
		return false;  
	}  
	winSize = CCDirector::sharedDirector()->getWinSize(); 
	
	m_pUiLayer = UILayer::create();
    addChild(m_pUiLayer);
        
    m_pWidget = dynamic_cast<Layout*>(CCUIHELPER->createWidgetFromJsonFile("StateLayer_1.json"));
    m_pUiLayer->addWidget(m_pWidget);
	
	// panel
	UIPanel *root = dynamic_cast<UIPanel*>(m_pUiLayer->getWidgetByName("root"));
	root->setPosition(ccp(winSize.width/2, winSize.height));
	root->setAnchorPoint(ccp(0.5f, 1.0f));

	speed = dynamic_cast<UIImageView*>(m_pUiLayer->getWidgetByName("speed"));
    speed->addReleaseEvent(this, coco_releaseselector(GameStateLayer::btnCallAccelerate));

    UIImageView* setting = dynamic_cast<UIImageView*>(m_pUiLayer->getWidgetByName("setting"));
    setting->addReleaseEvent(this, coco_releaseselector(GameStateLayer::btnCallSetting));

	this->setTouchEnabled(true);

	// init
	isAccelerated = false;
	moneyValue = GameUtil::instance()->getSetting()->getTotalMoney();;

	return true;  
} 

void GameStateLayer::btnCallSetting(CCObject* obj)  
{  
	GameUtil::instance()->pause();
}  

void GameStateLayer::btnCallAccelerate(CCObject* obj)
{
	if (isAccelerated) {
		speed->setTexture("accelerate.png");
		CCDirector::sharedDirector()->getScheduler()->setTimeScale(1.0);
	} else {
		speed->setTexture("normal.png");
		CCDirector::sharedDirector()->getScheduler()->setTimeScale(2.0);
	}
	isAccelerated = !isAccelerated;
}

void GameStateLayer::updateMoney()
{
	moneyValue = GameUtil::instance()->getSetting()->getTotalMoney();
	UILabelAtlas *money = dynamic_cast<UILabelAtlas*>(m_pUiLayer->getWidgetByName("money_value"));
	char c[50];  
    sprintf(c, "%d", moneyValue);
	money->setStringValue(c);
}

void GameStateLayer::getMoney(int money)
{
	GameUtil::instance()->getSetting()->earn(money);
	updateMoney();
}

void GameStateLayer::updateProgress(int max, int current)
{
	int duration = 5;
	if (current == 0) duration = 1; 
	
	
	int flagStart = 110;
	int flagEnd = -70;
	flagStart -= (200 * (current) / max);
	UIImageView* flag = dynamic_cast<UIImageView*>(m_pUiLayer->getWidgetByName("progress_flag"));
	CCFiniteTimeAction* action = CCMoveTo::create(duration, ccp(flagStart, 5));
	flag->runAction(action);
}